package servlet;

import utils.ZipUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
import java.nio.charset.StandardCharsets;

@WebServlet("/zip")
public class ZipServlet extends HttpServlet {


    private static final long serialVersionUID = 3822842786355254614L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ZipUtil z = new ZipUtil();
        String e_id = req.getParameter("e_id");
        String e_name = req.getParameter("e_name").replace(' ','+');
        String realPath = getServletContext().getRealPath("/file/");
        String[] srcDir = {realPath+e_id};
        String outDir = realPath+e_name+".zip";
        try {
            z.toZip(srcDir,outDir,true);
            String filename = e_name+".zip";
            String filepath = "/file/"+filename;

            byte[] bytes = filename.getBytes("UTF-8");
            filename = new String(bytes,"ISO8859-1");
            resp.setHeader("content-disposition", "attachment; filename="+filename);

            InputStream is = this.getServletContext().getResourceAsStream(filepath);
            ServletOutputStream os = resp.getOutputStream();
            int len = -1;
            byte[] buf = new byte[1024];
            while((len = is.read(buf)) != -1) {
                os.write(buf,0, len);
            }


            //关闭流
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
